import { Injectable } from '@nestjs/common';
import { PrismaService } from '../prisma.service';
import { Prisma } from '@prisma/client';

@Injectable()
export class MenuService {
    constructor(private prisma: PrismaService) { }


    // 创建菜单
    async create(data: Prisma.MenuCreateInput) {
        return this.prisma.menu.create({ data });
    }

    // 更新菜单
    async update(id: number, data: Prisma.MenuUpdateInput) {
        return this.prisma.menu.update({
            where: { id },
            data
        });
    }

    // 删除菜单
    async delete(id: number) {
        // 先删除子菜单
        await this.prisma.menu.deleteMany({
            where: { parentId: id }
        });

        return this.prisma.menu.delete({
            where: { id }
        });
    }

    // 获取菜单树
    async findTree() {
        const allMenus = await this.prisma.menu.findMany({
            orderBy: { sort: 'asc' }
        });

        return this.buildTree(allMenus);
    }

    // 构建树形结构
    private buildTree(menus: any[], parentId: number | null = null): any[] {
        return menus
            .filter(menu => menu.parentId === parentId)
            .map(menu => ({
                ...menu,
                children: this.buildTree(menus, menu.id)
            }))
            .sort((a, b) => a.sort - b.sort);
    }

    // 获取角色菜单
    async getRoleMenus(roleId: number) {
        const roleMenus = await this.prisma.roleMenu.findMany({
            where: { roleId },
            include: { menu: true }
        });

        return roleMenus.map(rm => rm.menu);
    }

    // 获取用户菜单
    async getUserMenus(userId: number) {
        const userRoles = await this.prisma.userRole.findMany({
            where: { userId },
            include: {
                role: {
                    include: {
                        roleMenus: {
                            include: {
                                menu: true
                            }
                        }
                    }
                }
            }
        });

        const menuSet = new Set();
        userRoles.forEach(ur => {
            ur.role.roleMenus.forEach(rm => {
                menuSet.add(rm.menu);
            });
        });

        const menus = Array.from(menuSet);
        return this.buildTree(menus);
    }
} 